<?php

namespace plugin\ycMassage\app\api\controller;

use app\common\service\UploadService;
use GuzzleHttp\Client;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageUserRealname;
use plugin\ycMassage\utils\BaiduHelper;
use plugin\ycMassage\utils\enum\Examine;
use plugin\ycMassage\utils\enum\NoticeType;
use plugin\ycMassage\utils\notice\Notice;
use support\Request;
use think\Exception;
use think\file\UploadedFile;

class RealnameController extends BaseController
{
    public function upload(Request $request)
    {
        # 获取上传文件
        $file = $request->file('file');
        $type=$request->post('type');
        $ocr=null;
        $baidu_ocr = getHpConfig('', $request->saas_appid, 'baidu_ocr');
        if(isset($baidu_ocr['state'])&&$baidu_ocr['state']){
            try {
                $access_token=BaiduHelper::getAccessToken($baidu_ocr);
                $url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=' . $access_token;
                $img = base64_encode(file_get_contents($file->getPathname()));
                $bodys = [
                    'id_card_side' => $type,
                    'image' => $img,
                    'detect_card'=>'true',
                    'detect_direction'=>'true'
                ];
                $client = new Client();
                $response = $client->post($url, [
                    'headers' => [
                        'Content-Type' => 'application/x-www-form-urlencoded'
                    ],
                    'form_params' => $bodys
                ]);
                $data = json_decode($response->getBody()->getContents(), true);
                if(isset($data['error_code'])){
                    throw new Exception($data['error_msg']);
                }
                $tempPath=runtime_path('temp');
                $tempFile=$tempPath.'/'.md5($file->getPathname()).'.png';
                file_put_contents($tempFile, base64_decode($data['card_image']));
                $file=new UploadedFile($tempFile,$file->getOriginalName(),'image/png',UPLOAD_ERR_OK);
                if($type=='front'){
                    $birthday=$data['words_result']['出生']['words']??'';
                    if(strlen($birthday)==8){
                        $birthday=substr($birthday,0,4).'-'.substr($birthday,4,2).'-'.substr($birthday,6,2);
                    }
                    $ocr=[
                        'name' => $data['words_result']['姓名']['words']??'',
                        'idcard_number' => $data['words_result']['公民身份号码']['words']??'',
                        'gender' => $data['words_result']['性别']['words']??'',
                        'nation' => $data['words_result']['民族']['words']??'',
                        'birthday' => $birthday,
                        'address' => $data['words_result']['住址']['words']??''
                    ];
                }else{
                    $expire_start=$data['words_result']['签发日期']['words']??'';
                    if(strlen($expire_start)==8){
                        $expire_start=substr($expire_start,0,4).'-'.substr($expire_start,4,2).'-'.substr($expire_start,6,2);
                    }
                    $expire_end=$data['words_result']['失效日期']['words']??'';
                    if(strlen($expire_end)==8){
                        $expire_end=substr($expire_end,0,4).'-'.substr($expire_end,4,2).'-'.substr($expire_end,6,2);
                    }
                    $expire_long=0;
                    if($expire_end=='长期有效'){
                        $expire_long=1;
                        $expire_end='';
                    }
                    $ocr=[
                        'issue' => $data['words_result']['签发机关']['words']??'',
                        'expire_start' => $expire_start,
                        'expire_end' => $expire_end,
                        'expire_long' => $expire_long,
                    ];
                }
            } catch (\Throwable $th) {
                return $this->fail($th->getMessage());
            }
        }
        # 上传附件
        try {
            $data    = UploadService::upload($file, '', $request->saas_appid, $request->uid, null, 1);
            if (!$data) {
                return $this->fail('上传失败');
            }
        } catch (\Throwable $th) {
            return $this->fail($th->getMessage());
        }
        $data['ocr']=$ocr;
        return $this->successFul('上传成功', $data);
    }
    public function submit(Request $request)
    {
        $data = $request->post();
        if(empty($data['name'])||empty($data['idcard_number'])||empty($data['front'])||empty($data['back'])){
            return $this->fail('请填写完整信息');
        }
        $model=MassageUserRealname::where(['uid'=>$request->uid,'saas_appid'=>$request->saas_appid])->find();
        if(!$model){
            $model=new MassageUserRealname();
            $model->uid=$request->uid;
            $model->saas_appid=$request->saas_appid;
        }elseif($model->examine===Examine::WAIT['value']){
            return $this->fail('实名信息正在审核中');
        }
        $model->name=$data['name'];
        $model->idcard_number=$data['idcard_number'];
        $model->gender=$data['gender'];
        $model->nation=$data['nation'];
        if($data['birthday']){
            $model->birthday=$data['birthday'];
        }
        $model->address=$data['address'];
        $model->issue=$data['issue'];
        if($data['expire_start']){
            $model->expire_start=$data['expire_start'];
        }
        $model->expire_long=$data['expire_long'];
        if(!$model->expire_long&&$data['expire_end']){
            $model->expire_end=$data['expire_end'];
        }
        $model->front=$data['front'];
        $model->back=$data['back'];
        $model->examine=Examine::WAIT['value'];
        if(!$model->save()){
            return $this->fail('提交失败');
        }
        $notice = new Notice();
        $notice->saas_appid = $model->saas_appid;
        $notice->role = ['ADMIN'];
        $notice->type = NoticeType::WORK_ORDER['value'];
        $notice->setData([
            'service_name' => '实名认证审核',
            'name' => $model->name . '(' . $model->uid . ')',
            'time' => date('Y-m-d H:i:s'),
        ]);
        $notice->send();
        return $this->success('提交成功');
    }
    public function info(Request $request)
    {
        $uid=$request->uid;
        $saas_appid=$request->saas_appid;
        $model=MassageUserRealname::where(['uid'=>$uid,'saas_appid'=>$saas_appid])->find();
        if(!$model){
            return $this->fail('未找到实名信息');
        }
        if($model->examine!==Examine::NO['value']){
            $model->name='*'.mb_substr($model->name,1);
            $model->idcard_number=substr_replace($model->idcard_number, '********', 6, 8);
        }
        return $this->successRes($model);
    }
}
